<template>
  <div class="register-container">
    <!-- 添加logo -->
    <div class="login-logo">
      <img src="../logo/1.png" alt="Logo" class="logo-img">
    </div>

    <el-card class="register-card" shadow="hover">
      <h2 class="register-title">注册系统</h2>
      <el-form ref="registerForm" :model="form" :rules="rules" class="register-form">
        <!-- 移除form-row和form-group外层容器 -->
        <el-form-item label="用户名" prop="username" class="inline-form-item">
          <el-input v-model="form.username" placeholder="请输入用户名" class="form-control"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password" class="inline-form-item">
          <el-input type="password" v-model="form.password" placeholder="请输入密码" class="form-control"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone" class="inline-form-item">
          <el-input v-model="form.phone" placeholder="请输入手机号" class="form-control"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email" class="inline-form-item">
          <el-input v-model="form.email" placeholder="请输入邮箱" class="form-control"></el-input>
        </el-form-item>
        <div class="form-row">
          <div class="form-group verification-group">
            <label class="form-label">验证码 <span class="required">*</span></label>
            <!-- 修改验证码按钮 -->
            <div class="verification-container">
              <input type="text" v-model="form.verificationCode" placeholder="请输入验证码"
                class="form-control verification-input" :class="{ 'error-border': submitted && !verificationCode }" />
              <div v-if="submitted && !verificationCode" class="error-message">请输入验证码</div>
              <button type="button" @click="sendVerificationCode" class="btn verification-btn"
                :disabled="countdown > 0">
                {{ countdown > 0 ? `${countdown}秒后重新发送` : '发送验证码' }}
              </button>
            </div>
          </div>
        </div>

        <el-form-item label="地区" prop="selectedAreaCode" class="inline-form-item">
          <el-cascader ref="areaCascader" v-model="form.selectedAreaCode" :options="options" size="default"
            placeholder="请选择地区" @change="handleChange" @mouseenter="handleCascaderMouseEnter"
            :props="{ label: 'label', value: 'value', children: 'children', expandTrigger: 'hover' }"
            class="form-control"></el-cascader>
        </el-form-item>

        <div class="form-row">
          <div class="form-group half-width">
            <label class="form-label" for="userRole">用户角色 <span class="required">*</span></label>
            <select id="userRole" v-model="form.userRole" class="form-control">
              <option value="REGULAR_USER">普通用户</option>
              <option value="DEVICE_ADMINISTRATOR">设备管理员</option>
              <option value="REPAIR_USER">维护人员</option>
              <option value="SYSTEM_ADMINISTRATOR">系统管理员</option>
            </select>
          </div>
        </div>

      </el-form>
      <div class="form-actions">
        <button type="button" @click="submitForm" class="btn submit-btn">提交</button>
        <button type="button" @click="resetForm" class="btn cancel-btn">取消</button>
      </div>
    </el-card>
  </div>

  <div v-if="showSystemError" class="system-error-modal">
    <div class="modal-content">
      <div class="error-icon">⚠️</div>
      <div class="error-message">{{ systemErrorMsg }}</div>
      <button @click="closeError" class="confirm-btn">确定</button>
    </div>
  </div>
</template>

<script>
// 导入Element Plus组件
import { ElCard, ElMessageBox, ElForm, ElFormItem, ElInput } from 'element-plus';
import { useRouter } from 'vue-router';
import api from '@/utils/api';
import { codeToText, regionData as areaList } from 'element-china-area-data';

export default {
  data() {
    return {
      form: {
        username: '',
        password: '',
        phone: '',
        email: '',
        verificationCode: '',
        userRole: 'REGULAR_USER',
        // 添加缺少的请求参数
        code: 0,
        province: '',
        city: '',
        town: '',
        permission: '',
        selectedAreaCode: []
      },
      // 添加表单验证规则
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              console.log('自定义验证器被调用，值:', value, '类型:', typeof value);
              const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
              const isValid = emailRegex.test(value);
              console.log('自定义验证器正则匹配结果:', isValid);
              if (emailRegex.test(value)) {
                callback();
              } else {
                callback('请输入有效的邮箱地址');
              }
            }, trigger: ['blur', 'change']
          }
        ],
        verificationCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        selectedAreaCode: [
          { required: true, message: '请选择地区', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              console.log('地区验证值:', value);
              if (Array.isArray(value) && value.length >= 3) {
                callback();
              } else {
                callback(new Error('请选择完整地区（省/市/区）'));
              }
            },
            trigger: 'change'
          }
        ]
      },
      countdown: 0,

      options: areaList,
      showSystemError: false,
      systemErrorMsg: ''
    };
  },
  created() {
    this.router = useRouter();
  },
  methods: {
    sendVerificationCode() {
      console.log('发送验证码按钮点击');
      // 验证邮箱格式
      console.log('开始验证邮箱格式');
      this.form.email = this.form.email ? this.form.email.trim() : '';
      console.log('验证前邮箱值:', this.form.email, '长度:', this.form.email.length);
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      console.log('邮箱正则匹配结果:', emailRegex.test(this.form.email));
      // 直接进行邮箱格式验证，绕过表单验证
      const trimmedEmail = this.form.email.trim();
      const isValid = emailRegex.test(trimmedEmail);
      console.log('修剪后的邮箱:', trimmedEmail);
      console.log('直接验证结果:', isValid);
      if (!isValid) {
        ElMessageBox.alert('请输入有效的邮箱地址', '验证失败', {
          confirmButtonText: '确定',
          type: 'error'
        });
        return;
      }
      console.log('邮箱验证通过，开始发送验证码');

      // 设置倒计时
      this.countdown = 60;
      console.log('设置倒计时为60秒');
      const timer = setInterval(() => {
        this.countdown--;
        console.log('倒计时更新:', this.countdown);
        if (this.countdown <= 0) {
          clearInterval(timer);
          console.log('倒计时结束，清除定时器');
        }
      }, 1000);

      // 发送验证码请求
      const codeVO = { email: this.form.email, mailTitle: 'SEND_CODE_REGISTRATION' };
      console.log('发送验证码请求参数:', { codeVO });
      api.post('/users/sendCode', {
        email: this.form.email,
        mailTitle: 'SEND_CODE_REGISTRATION'
      })
        .then((response) => {
          console.log('验证码发送成功响应:', response.data);
          ElMessageBox.alert('验证码已发送至邮箱', '系统提示', {
            confirmButtonText: '确定',
            type: 'info',
            center: true
          });
        })
        .catch(error => {
          clearInterval(timer);
          this.countdown = 0;
          console.error('验证码发送失败:', error.response ? error.response.data : error.message);
          this.systemErrorMsg = '验证码发送失败: ' + (error.response?.data?.message || '请稍后重试');
          this.showSystemError = true;
        });
    },

    handleChange(value) {

      console.log('地区选择值:', value);
      if (value && value.length >= 3) {
        // 将数字编码转换为地区名称字符串
        this.form.province = codeToText[value[0]];
        this.form.city = codeToText[value[1]];
        this.form.town = codeToText[value[2]];
        console.log('转换后的地区名称:', this.form.province, this.form.city, this.form.town);
      }
      // 手动触发地区字段验证并输出结果
      this.$refs.registerForm.validateField('selectedAreaCode', (error) => {
        console.log('地区验证结果:', error ? '失败: ' + error : '成功');
      });
    },

    async submitForm() {


      try {
        console.log('提交表单时地区值:', this.form.selectedAreaCode);
        // 使用表单验证
        const isValid = await this.$refs.registerForm.validate();
        console.log('表单整体验证结果:', isValid);

        // 表单验证通过，发送注册请求
        // 仅保留后端要求的必要字段
        // 仅发送有值的字段，避免空字符串导致后端验证错误
        const requestData = {
          username: this.form.username,
          password: this.form.password,
          ...(this.form.phone && { phone: this.form.phone }),
          ...(this.form.email && { email: this.form.email }),
          ...(this.form.verificationCode && { code: this.form.verificationCode }),
          ...(this.form.province && { province: this.form.province }),
          ...(this.form.city && { city: this.form.city }),
          ...(this.form.town && { town: this.form.town }),
          ...(this.form.userRole && { permission: this.form.userRole })
        };
        // 详细日志 - 请求前
        console.log('=== 注册请求即将发送 ===');
        console.log('请求URL:', '/users/registration');
        console.log('请求方法:', 'POST');
        console.log('最终发送请求数据:', JSON.stringify(requestData, null, 2));
        console.log('请求数据类型检查:', Object.entries(requestData).map(([k, v]) => `${k}: ${typeof v}`).join(', '));
        console.log('=========================');
        const response = await api.post('/users/registration', requestData);
        // 详细日志 - 请求后
        console.log('=== 注册请求响应 ===');
        console.log('响应状态码:', response.status);
        console.log('响应数据:', JSON.stringify(response.data, null, 2));
        console.log('=====================');

        // 根据新的响应结构处理
        if (response.code === 200) {
          ElMessageBox.alert('注册成功，请登录', '系统提示', {
            confirmButtonText: '确定',
            type: 'success',
            center: true
          }).then(() => {
            this.$router.push('/login');
          });
        } else {
          this.systemErrorMsg = response.msg || '注册失败';
          this.showSystemError = true;
        }
      } catch (error) {
        // 增强错误日志 - 捕获完整的后端验证错误
        console.error('=== 注册请求错误详情 ===');
        console.error('状态码:', error.response?.status);
        console.error('响应数据:', JSON.stringify(error.response?.data, null, 2));
        console.error('响应头:', error.response?.headers);
        console.error('错误消息:', error.message);
        console.error('完整错误对象:', error);
        console.error('=========================');
        if (error.name !== 'ValidationError') {
          this.verificationCode = '';
          this.systemErrorMsg = '注册失败: ' + (error.response?.data?.message || error.message || '未知错误');
          this.showSystemError = true;
        }
      }
    },
    resetForm() {
      this.username = '';
      this.password = '';
      this.phone = '';
      this.email = '';
      this.verificationCode = '';
      this.router.push('/login');
    },
    closeError() {
      this.showSystemError = false;
    },
    testErrorHandling() {
      try {
        throw new Error('测试错误处理流程');
      } catch (error) {
        this.verificationCode = '';
        this.systemErrorMsg = '系统提示: 后端服务连接失败，请稍后重试';
        this.showSystemError = true;
        console.log('错误处理已执行，验证码已清空');
        console.error('错误详情:', error);
      }
    }
  }
};

</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  position: relative;
  overflow: hidden;
  padding: 20px;
}

.register-container::before,
.register-container::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

.register-container::before {
  background: linear-gradient(135deg, #0a2463 0%, #2980b9 35%, #3e92cc 65%, #5dade2 100%);
  animation: gradientShift 15s ease infinite;
  background-size: 400% 400%;
}

.register-container::after {
  background-image:
    radial-gradient(circle at 50% 50%, rgba(255, 255, 255, 0.5) 0%, rgba(255, 255, 255, 0) 60%),
    radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 40%),
    radial-gradient(circle at 70% 70%, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 40%);
  animation: vortexRotate 20s linear infinite;
}

@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

@keyframes vortexRotate {
  0% {
    transform: rotate(0deg) scale(1);
  }

  50% {
    transform: rotate(180deg) scale(1.1);
  }

  100% {
    transform: rotate(360deg) scale(1);
  }
}

.register-card {
  width: 100%;
  max-width: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 25px;
}

.register-title {
  text-align: center;
  margin: 0 0 25px 0;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
  color: #303133;
}

/* 表单样式 */
.form-row {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.form-group {
  flex: 1;
  min-width: 0;
  margin-bottom: 20px;
}

.required {
  color: red;
  margin-left: 2px;
}

.form-label {
  display: block;
  margin-bottom: 7px;
  font-weight: 500;
  color: #606266;
}

/* 仅移除特定输入框的边框 */
.form-control[name="username"],
.form-control[name="password"],
.form-control[name="phone"],
.form-control[name="email"] {
  border: none;
  outline: none;
  background: transparent;
  padding: 10px 0;
  border-bottom: 1px solid #e0e0e0;
  border-radius: 0;
}

.form-control[name="username"]:focus,
.form-control[name="password"]:focus,
.form-control[name="phone"]:focus,
.form-control[name="email"]:focus {
  border-bottom: 1px solid #1890ff;
  box-shadow: none;
}

/* 统一边框和文字颜色为更浅的灰色 */
.form-control[name="verificationCode"],
.form-control.select,
.form-control[name="region"] {
  border: 1px solid #f0f0f0;
  /* 更浅的灰色边框，与手机号输入框底部边框视觉一致 */
  padding: 10px;
  border-radius: 4px;
  color: #b0b0b0;
  /* 更浅的文字颜色 */
}

/* 下拉菜单选项文字颜色保持清晰可读 */
.form-control.select option,
.form-control[name="region"] option {
  color: #666;
  /* 选项文字颜色稍深以确保可读性 */
}

/* 按钮样式统一 */
.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 30px;
}

.btn {
  padding: 12px 0;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  flex: 1;
  border: none;
}

.submit-btn {
  background-color: #409eff;
  color: white;
}

.cancel-btn {
  background-color: #f5f7fa;
  color: #606266;
}

/* 验证码区域保持7:3比例 */
.verification-container {
  display: flex;
  gap: 10px;
}

.verification-input {
  flex: 7;
}

.verification-btn {
  flex: 3;
  background-color: #409eff;
  color: white;
  padding: 12px 0;
}

.system-error-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  width: 300px;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 15px;
  color: #ffc107;
}

.error-message {
  color: red;
  font-size: 12px;
  margin-top: 4px;
  text-align: left;
}

.confirm-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.inline-form-item {
  display: inline-block;
  width: 48%;
  margin-right: 4%;
  margin-bottom: 20px;
}

.inline-form-item:nth-child(even) {
  margin-right: 0;
}

.el-form-item[label="选择地区"] {
  width: 100%;
}

/* 添加错误状态样式 */
.error-border {
  border-color: red !important;
}

/* 添加logo样式 */
.login-logo {
  position: absolute;
  top: 25px;
  left: 25px;
  z-index: 1;
}

.logo-img {
  max-width: 180px;
  max-height: 120px;
  width: auto;
  height: auto;
  object-fit: contain;
}

/* 调整卡片位置避免重叠 */
.register-card {
  margin-top: 60px;
}

/* 确保容器支持绝对定位 */
.register-container {
  position: relative;
}
</style>
